/*
main 包
 */

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

// User 用户
type User struct {
	Name     string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
	Age      int    `form:"age" json:"age" binding:"required"`
}

type object struct {
	name   string // 名字
	adress string // 地址
}

func main() {
	router := gin.Default()
	router.LoadHTMLFiles("./login.html", "./file.html")

	router.GET("/login", func(context *gin.Context) {
		context.HTML(http.StatusOK, "login.html", nil)
	})
	router.POST("/login", func(context *gin.Context) {
		var user User
		if err := context.ShouldBind(&user); err == nil {
			fmt.Printf("login info:%#v\n", user)
			context.JSON(http.StatusOK, gin.H{
				"user":     user.Name,
				"password": user.Password,
				"age":      user.Age,
			})
		} else {
			context.JSON(http.StatusBadRequest,
				gin.H{"error": err.Error()})
		}
	})

	router.GET("/upload", func(context *gin.Context) {
		context.HTML(http.StatusOK, "file.html", nil)
	})

	//router.POST("/upload", func(context *gin.Context) {
	//	f, err := context.FormFile("f1")
	//	if err!=nil {
	//		context.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
	//		return
	//	}
	//	filename := f.Filename
	//	dst := fmt.Sprintf("./%s", filename)
	//	context.SaveUploadedFile(f, dst)
	//	context.JSON(http.StatusOK, gin.H{
	//		"message": fmt.Sprintf("'%s' uploaded!", f.Filename),
	//	})
	//
	//})

	router.POST("/upload", func(context *gin.Context) {
		form, _ := context.MultipartForm()
		files, _ := form.File["file"]

		for index, file := range files {
			log.Println(file.Filename)
			dst := fmt.Sprintf("./%s", file.Filename, index)
			// 上传文件到指定的目录
			context.SaveUploadedFile(file, dst)
		}
		context.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})

	router.GET("/test", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "http://www.sogo.com/")
	})

	router.Run(":9000")
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
